const express = require('express')
const http = require('http')
const { Server } = require('socket.io')

const app = express()
const server = http.createServer(app)

app.get('/', (req, res) => {
	res.send('Hello World!')
})

const io = new Server(server, {
	cors: {
		origin: '*' // 生产环境应限制为具体域名
	}
})

io.on('connection', socket => {
	console.log('用户已连接:', socket.id)

	// 监听聊天消息
	socket.on('chatMessage', msg => {
		// 广播给所有客户端（包括发送者）
		io.emit('chatMessage', {
			...msg,
			id: Date.now()
		})
	})

	socket.on('disconnect', () => {
		console.log('用户断开连接:', socket.id)
	})
})

const PORT = process.env.PORT || 3000
server.listen(PORT, () => {
	console.log(`Socket服务器运行在: http://localhost:${PORT}`)
})
